package com.chuangke.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.chuangke.admin.constant.SysConstant;
import com.chuangke.admin.dto.PasswdRequest;
import com.chuangke.admin.dto.UserPassResetBean;
import com.chuangke.admin.entity.SysUser;
import com.chuangke.admin.service.SysUserRoleQueryService;
import com.chuangke.admin.service.SysUserService;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.common.http.HttpResult;
import com.chuangke.common.utils.PasswordUtils;
import com.chuangke.common.utils.SecurityUtils;
import com.chuangke.framework.model.BasicModel;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户控制器
 * 
 * @author chuangke
 * @date Oct 29, 2018
 */
@RestController
@RequestMapping("user")
public class SysUserController {

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleQueryService sysUserRoleQueryService;

	@PreAuthorize("hasAuthority('sys:user:add') AND hasAuthority('sys:user:edit')")
	@PostMapping(value = "/save")
	public HttpResult save(@RequestBody SysUser record) {
		SysUser user = sysUserService.findById(record.getId());
		if (user != null) {
//			if (SysConstants.ADMIN.equalsIgnoreCase(user.getName())) {
//				return HttpResult.error("超级管理员不允许修改!");
//			}
		}
		if (record.getPassword() != null) {
			String salt = PasswordUtils.getSalt();
			if (user == null) {
				// 新增用户
				if (sysUserService.findByName(record.getName()) != null) {
					return HttpResult.error("用户名已存在!");
				}
				String password = PasswordUtils.encode(true,record.getPassword(), salt);
				record.setSalt(salt);
				record.setPassword(password);
			} else {
				// 修改用户, 且修改了密码
				if (!record.getPassword().equals(user.getPassword())) {
					String password = PasswordUtils.encode(record.getPassword(), salt);
					record.setSalt(salt);
					record.setPassword(password);
				}
			}
		}
		sysUserService.save(record);
		return HttpResult.ok();
	}

	@PreAuthorize("hasAuthority('sys:user:add') AND hasAuthority('sys:user:edit')")
	@PostMapping(value = "/savebaseinfo")
	public HttpResult updateBaseInfo(@RequestBody SysUser record) {
//		if (SysConstants.ADMIN.equalsIgnoreCase(record.getName())) {
//			return HttpResult.error("超级管理员不允许修改!");
//		}
		sysUserService.updateBaseInfo(record);
		return HttpResult.ok();
	}

	@PreAuthorize("hasAuthority('sys:user:delete')")
	@PostMapping(value = "/delete")
	public HttpResult delete(@RequestBody List<SysUser> records) {
		for (SysUser record : records) {
			SysUser sysUser = sysUserService.findById(record.getId());
			if (sysUser != null && SysConstant.ADMIN.equalsIgnoreCase(sysUser.getName())) {
				return HttpResult.error("超级管理员不允许删除!");
			}
		}
		sysUserService.delete(records);
		return HttpResult.ok();
	}

	@PreAuthorize("hasAuthority('login:action')")
	@GetMapping(value = "/findByName")
	public HttpResult findByUserName(@RequestParam String name) {
		return HttpResult.ok(sysUserService.findByName(name));
	}

	@PreAuthorize("hasAuthority('login:action')")
	@GetMapping(value = "/findPermissions")
	public HttpResult findPermissions(@RequestParam String name) {
		return HttpResult.ok(sysUserService.findPermissions(name));
	}

	@PreAuthorize("hasAuthority('login:action')")
	@GetMapping(value = "/findUserRoles")
	public HttpResult findUserRoles(@RequestParam String userId) {
		return HttpResult.ok(sysUserRoleQueryService.findByUserId(userId));
	}

	@PreAuthorize("hasAuthority('sys:user:view') OR hasAuthority('login:action')")
	@PostMapping(value = "/findPage")
	public HttpResult findPage(@RequestBody Map<String,Object> params) {
		return HttpResult.ok(sysUserService.page(new CkPageQuery(params)));
	}

	@PreAuthorize("hasAuthority('sys:user:view') OR hasAuthority('login:action')")
	@PostMapping(value = "/findowndeptPage")
	public HttpResult findOwnDeptPage(@RequestBody Map<String,Object> params) {
		SysUser sysUser = sysUserService.findById(SecurityUtils.getUserId());
		params.put("deptId",  sysUser.getDeptId());
		return HttpResult.ok(sysUserService.page(new CkPageQuery(params)));
	}

	@PreAuthorize("hasAuthority('sys:user:edit')")
	@PostMapping("/avatar")
	public HttpResult achievement(@RequestBody String avatarBase64) {
		sysUserService.avatar(avatarBase64) ;
		return HttpResult.ok();
	}

	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping(value = "/passwd")
	public HttpResult passwd(@RequestBody PasswdRequest passwdRequest) {
		if (!passwdRequest.getNewpwd().equals(passwdRequest.getNewpwd2())) {
			return HttpResult.error("两次输入的密码不匹配!");
		}
		String userId = SecurityUtils.getUserId();
		SysUser user = sysUserService.findById(userId);
		String password = PasswordUtils.encode(false,passwdRequest.getPwd(), user.getSalt());
		if (!password.equals(user.getPassword())) {
			return HttpResult.error("密码错误!");
		}

		sysUserService.resetPassword(passwdRequest.getNewpwd(), Collections.singletonList(userId)) ;
		return HttpResult.ok();
	}

	@PreAuthorize("hasAuthority('sys:user:delete')")
	@GetMapping(value = "/changeStatus")
	public HttpResult changeStatus(@RequestParam List<String> ids, @RequestParam String status) {
		return HttpResult.ok(sysUserService.changeStatus(ids, status));
	}

	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping(value = "/resetpass")
	public HttpResult resetPassword(@RequestBody UserPassResetBean uprb) {
		if (StrUtil.isBlank(uprb.getPassword())) {
			throw new ChuangkeException("请输入密码");
		}

		List<String> userIdList = uprb.getUserIdList();
		if (CollectionUtils.isEmpty(userIdList)) {
			userIdList = sysUserService.findMap().values().stream().filter(user -> !"admin".equals(user.getName()))
					.map(BasicModel::getId).collect(Collectors.toList());
		}
		sysUserService.resetPassword(uprb.getPassword(), userIdList);
		return HttpResult.ok();
	}
}
